class X { public: private: int &r; }; X abc; /*Object abc of type X*/ /*Compile error */ int main() { int ni; int const i; /*ILLEGAL*/ int const i=5; /*Top-level const*/ int const *pi1 = &i; /*Low-level const*/ int const * const pi2=&i; /*Both top and low-level const*/ int const *haha = pi2; /*Legal*/ int const &cr1=i; int const &cr2=i; }
TOP-LEVEL CONST IS CONST ON THE SURFACE in C++ you cannot assign a low-level const to a non const BUT you can assign a top level const to a non const
References must be initialized, they have the properties of a const object.
As long as the variable is initialized in construction, it should be fine.
void mutate(std::string &str) { } void observe(const std::string & str) { //reference can be used instead of making a copy as it is less taxing on the system //can pass in constant strings //best to use instead of making a copy } int main() { int&const test; //compile-time error }
If you return by value in an operator overload, you are invoking a copy constructor. Therefore:
if an operator overload for adding a and b together occurs and res is the return value
res contains the addition of a copy of a and a copy of b
then unnamed_obj becomes a copy of res
c=a+b;
is
c=unnamed_obj=a+b;
copy elison is used so that unnamed_obj doesn't have to be created. BUT c is still going to make a copy of res.
this is where && comes in.
copy elision!
vector &&x will basically make the pointer of the assigned thing point to x, then have the pointer of x point to null. Basically, stealing a dude's stuff and then murdering him.
vector &&x is gonna be an RVALUE
remember, rvalues are values that you cannot get an address of and are going to die.
move semantics lets c IMMEDIATELY get the values of a+b.
Str::Str(Str&& rhs) : mLen(rhs.mLen) mPtr(rhs.mPtr) { rhs.mPtr = nullptr; //this is so that rhs can be deleted safely. }
Str tmp = std::move(lhs); //this lets tmp steal from lhs
rvalue references are ONLY used in move semantics.
int const & ri = double WORKS
int & ri = double DOES NOT